package cn.iocoder.yudao.module.member.controller.admin.job;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.SortingField;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.member.controller.admin.job.vo.*;
import cn.iocoder.yudao.module.member.convert.job.MemberJobConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.job.MemberJobDO;
import cn.iocoder.yudao.module.member.service.job.MemberJobService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Api(tags = "管理后台 -运营端- 招聘职位")
@RestController
@RequestMapping("/member/job")
@Validated
@Slf4j
public class MemberJobController {

    @Resource
    private MemberJobService jobService;

    @PostMapping("/create")
    @ApiOperation("创建招聘职位")
    public CommonResult<Long> createJob(@Valid @RequestBody MemberJobCreateReqVO createReqVO) {
        return success(jobService.createJob(createReqVO));
    }

    @PostMapping("/admin/createJob")
    @ApiOperation("创建招聘职位")
    public CommonResult<Long> createJob1(@Valid @RequestBody MemberJobCreateReqVO createReqVO) {
        return this.createJob(createReqVO);
    }

    @PutMapping("/update")
    @ApiOperation("更新招聘职位")
    @TenantIgnore
    public CommonResult<Boolean> updateJob(@Valid @RequestBody MemberJobUpdateReqVO updateReqVO) {
        jobService.updateJob(updateReqVO);
        return success(true);
    }


    @PutMapping("/updateJobFixed")
    @ApiOperation("更新职位定时暂停发布")
    @TenantIgnore
    public CommonResult<Boolean> updateJobFixed(@Valid @RequestBody MemberJobUpdateVO updateReqVO) {
        if(updateReqVO.getTimingStatus()!=0 && StringUtils.isBlank(updateReqVO.getFixedTime())){
            return error("定时时间不能为空");
        }
        jobService.updateJobFixed(updateReqVO.getId(),updateReqVO.getTimingStatus(),updateReqVO.getFixedTime());
        return success(true);
    }

    @PutMapping("/updateOrderNum")
    @ApiOperation("更新职位排序")
    @TenantIgnore
    public CommonResult<Boolean> updateOrderNum(@RequestBody Map<String,Object> param) {
        Long id = MapUtils.getLong(param, "id");
        if(id==null){
            return error("ID不能为空");
        }
        jobService.updateOrderNum(id);
        return success(true);
    }

    @PutMapping("/oper-update")
    @ApiOperation("更新招聘职位")
    @TenantIgnore
    public CommonResult<Boolean> operUpdate(@Valid @RequestBody MemberJobUpdateReqVO updateReqVO) {
        jobService.updateJob(updateReqVO);
        return success(true);
    }


    @PutMapping("/admin/editJob")
    @ApiOperation("更新招聘职位")
    @TenantIgnore
    public CommonResult<Boolean> editJob(@Valid @RequestBody MemberJobUpdateReqVO updateReqVO) {
        this.updateJob(updateReqVO);
        return success(true);
    }


    @DeleteMapping("/delete")
    @ApiOperation("删除招聘职位")
    @TenantIgnore
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = Long.class)
    public CommonResult<Boolean> deleteJob(@RequestParam("id") Long id) {
        jobService.deleteJob(id);
        return success(true);
    }

    @DeleteMapping("/admin/delete")
    @ApiOperation("删除招聘职位")
    @TenantIgnore
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = Long.class)
    public CommonResult<Boolean> deleteJob1(@RequestParam("id") Long id) {
        this.deleteJob(id);
        return success(true);
    }

    @GetMapping("/oper-get")
    @ApiOperation("获得招聘职位")
    @TenantIgnore
    public CommonResult<MemberJobRespVO> getOperJob(@RequestParam("id") Long id) {
        MemberJobDO job = jobService.getJob(id,0);
        return success(MemberJobConvert.INSTANCE.convert(job));
    }

    @GetMapping("/get")
    @ApiOperation("获得招聘职位")
    @TenantIgnore
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
    public CommonResult<MemberJobRespVO> getJob(@RequestParam("id") Long id) {
        MemberJobDO job = jobService.getJob(id,0);
        return success(MemberJobConvert.INSTANCE.convert(job));
    }


    @GetMapping("/admin/jobDetail")
    @ApiOperation("获得招聘职位")
    @TenantIgnore
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
    public CommonResult<MemberJobRespVO> getJob1(@RequestParam("id") Long id) {
        return this.getJob(id);
    }

    @GetMapping("/list")
    @ApiOperation("获得招聘职位列表")
    @TenantIgnore
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    public CommonResult<List<MemberJobRespVO>> getJobList(@RequestParam("ids") Collection<Long> ids) {
        List<MemberJobDO> list = jobService.getJobList(ids);
        return success(MemberJobConvert.INSTANCE.convertList(list));
    }

    @PostMapping("/page")
    @ApiOperation("获得招聘职位分页")
    @TenantIgnore
    public CommonResult<PageResult<MemberJobRespVO>> getJobPage(@RequestBody MemberJobPageReqVO pageVO) {
        PageResult<MemberJobDO> pageResult = jobService.getJobPage(pageVO);
        return success(MemberJobConvert.INSTANCE.convertPage(pageResult));
    }

    @PostMapping("/admin/getCompanys")
    @ApiOperation("获得招聘职位分页")
    @TenantIgnore
    public CommonResult<PageResult<MemberJobRespVO>> getCompanys(@RequestBody MemberJobPageReqVO pageVO) {
        return this.getJobPage(pageVO);
    }

    @PostMapping("/admin/export-excel")
    @ApiOperation("导出招聘职位 Excel")
    @OperateLog(type = EXPORT)
    public void exportJobExcel(@RequestBody MemberJobExportReqVO exportReqVO,
                               HttpServletResponse response) throws IOException {
        List<MemberJobDO> list = jobService.getJobList(exportReqVO);
        // 导出 Excel
        List<JobExcelVO> datas = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)){
            list.stream().forEach(m->{
                JobExcelVO j=new JobExcelVO();
                j.setJobName(m.getJobName());
                j.setCompanyName(m.getCompanyName());
                String city = m.getCity();
                String address="";
                if(StringUtils.isNotBlank(city)){
                    JSONArray jsonArray= JSONObject.parseArray(city);
                    if(null!=jsonArray && jsonArray.size()>0){
                        for (int i = 0; i < jsonArray.size(); i++) {
                            address+=jsonArray.getString(i);
                        }
                    }
                }
                j.setWorkAddress(address+m.getWorkAddress());
                j.setDepartment(m.getDepartment());
                j.setOperation(m.getOperation());
                if(1==m.getIsHot()){
                    j.setIsHot("是");
                }else{
                    j.setIsHot("否");
                }
                if(1==m.getIsNew()){
                    j.setIsNew("是");
                }else{
                    j.setIsNew("否");
                }
                j.setUpdateTime(m.getUpdateTime());
                j.setJobDescription(m.getJobDescription());
                datas.add(j);
            });
        }
        String sheetName="";
        if(exportReqVO.getStatuss().contains("2")){
            sheetName="职位信息-发布中";
        }else if(exportReqVO.getStatuss().contains("3")){
            sheetName="职位信息-暂停发布";
        }else{
            sheetName="职位信息-未发布";
        }
        ExcelUtils.write(response, "招聘职位.xls", sheetName, JobExcelVO.class, datas);
    }

    @PostMapping("/admin/jobWaitExamineList")
    @ApiOperation("获得待发布招聘职位分页")
    public CommonResult<PageResult<MemberJobRespVO>> getJobWaitExaminePage(@RequestBody MemberJobPageReqVO pageVO) {
        PageResult<MemberJobDO> pageResult = jobService.getJobWaitExaminePage(pageVO, pageVO.getFlag());
        return success(MemberJobConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/recoveryMemberJobPage")
    @ApiOperation("回收站(招聘职位)")
    @TenantIgnore
    public CommonResult<PageResult<MemberJobRespVO>> recoveryMemberJobPage(@Valid MemberJobPageReqVO pageVO) {
        PageResult<MemberJobDO> pageResult = jobService.getMemberJobPage(pageVO);
        return success(MemberJobConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/getRecoveryMemberJobById")
    @ApiOperation("回收站(根据ID查看)")
    @TenantIgnore
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1", dataTypeClass = Long.class)
    public CommonResult<MemberJobRespVO> getRecoveryMemberJobById(@RequestParam("id") Long id) {
        MemberJobDO memberJobDO = jobService.getRecoveryMemberJobById(id);
        MemberJobRespVO memberJobRespVO=null;
        if(null!=memberJobDO){
            memberJobRespVO=new MemberJobRespVO();
            BeanUtils.copyProperties(memberJobDO,memberJobRespVO);
        }
        return success(memberJobRespVO);
    }
    @PutMapping("/updateBatchRecoveryMemberJob")
    @ApiOperation("回收站(批量还原)")
    @TenantIgnore
    public CommonResult<Boolean> updateBatchRecoveryMemberJob( @RequestBody MemberJobidsVO memberJobidsVO) {
        if(CollectionUtils.isEmpty(memberJobidsVO.getIds())){
            return error("请先选择记录");
        }
        jobService.updateBatchRecoveryMemberJob(memberJobidsVO.getIds());
        return success(true);
    }



    @PostMapping("/admin/getJobWaitPage")
    @ApiOperation("获得待发布招聘职位分页")
    @TenantIgnore
    public CommonResult<PageResult<MemberJobRespVO>> getJobWaitPage(@RequestBody MemberJobPageReqVO pageVO) {
        if(null!=pageVO.getIsHot()&& 1==pageVO.getIsHot()){
            SortingField s=new SortingField();
            s.setField("j.hot_weight");
            s.setOrder("desc");
            pageVO.setSortField(s);
        }
        if(null!=pageVO.getIsNew()&& 1==pageVO.getIsNew()){
            SortingField s=new SortingField();
            s.setField("j.new_weight");
            s.setOrder("desc");
            pageVO.setSortField(s);
        }
        if(null==pageVO.getSortField()){
            SortingField s=new SortingField();
            s.setField("j.update_time");
            s.setOrder("desc");
            pageVO.setSortField(s);
        }
        PageResult<MemberJobDO> pageResult = jobService.getJobWaitExaminePage(pageVO, pageVO.getFlag());
        return success(MemberJobConvert.INSTANCE.convertPage(pageResult));
    }

    @PostMapping("/admin/examinJob")
    @ApiOperation("审核职位")
    @TenantIgnore
    public CommonResult<Boolean> examinJob(@RequestBody MemberJobUpdateReqVO updateReqVO) {
        jobService.examinJob(updateReqVO);
        return success(true);
    }

    @PostMapping("/admin/jobExamineDoneList")
    @ApiOperation("获得已发布招聘职位分页")
    @TenantIgnore
    public CommonResult<PageResult<MemberJobRespVO>> jobExamineDoneList(@RequestBody MemberJobPageReqVO pageVO) {
        PageResult<MemberJobDO> pageResult = jobService.getJobWaitExaminePage(pageVO, pageVO.getFlag());
        return success(MemberJobConvert.INSTANCE.convertPage(pageResult));
    }

    @PostMapping("/admin/checkJobList")
    @ApiOperation("获得招聘职位列表分页")
    @TenantIgnore
    public CommonResult<PageResult<MemberJobRespVO>> checkJobList(@RequestBody MemberJobPageReqVO pageVO) {
        PageResult<MemberJobDO> pageResult = jobService.getJobPage(pageVO);
        return success(MemberJobConvert.INSTANCE.convertPage(pageResult));
    }

    @PostMapping("/admin/updateJobDate")
    @ApiOperation("刷新职位")
    @TenantIgnore
    public CommonResult<Boolean> updateJobDate(@RequestBody MemberJobUpdateReqVO updateReqVO) {
        MemberJobDO memberJobDO=jobService.getJob(updateReqVO.getId());
        BeanUtils.copyProperties(memberJobDO,updateReqVO);
        updateReqVO.setPublishTime(new Date());
        jobService.updateJob(updateReqVO);
        return success(true);
    }

    @PostMapping("/admin/updateJobDateBach")
    @ApiOperation("批量刷新职位")
    @TenantIgnore
    public CommonResult<Boolean> updateJobDateBach(@RequestBody List<MemberJobUpdateReqVO> updateReqVOs) {
        for (MemberJobUpdateReqVO memberJobUpdateReqVO:updateReqVOs){
            MemberJobDO memberJobDO=jobService.getJob(memberJobUpdateReqVO.getId());
            BeanUtils.copyProperties(memberJobDO,memberJobUpdateReqVO);
            memberJobUpdateReqVO.setPublishTime(new Date());
            jobService.updateJob(memberJobUpdateReqVO);
        }
        return success(true);
    }

    @PutMapping("/admin/setJobTopStatus")
    @ApiOperation("批量置顶/取消置顶职位")
    @TenantIgnore
    public CommonResult<Boolean> setJobsTopStatus(@RequestBody MemberJobidsVO memberJobidsVO) {
        jobService.setJobsTopStatus(memberJobidsVO.getIds(), memberJobidsVO.getStatus());
        return success(true);
    }

    @PutMapping("/admin/setJobStatus")
    @ApiOperation("批量修改职位状态")
    @TenantIgnore
    public CommonResult<Boolean> setJobStatus(@RequestBody MemberJobidsVO memberJobidsVO) {
        jobService.setJobStatus(memberJobidsVO.getIds(),memberJobidsVO.getStatus());
        return success(true);
    }
    //todo 批量导入


    @DeleteMapping("/admin/deleteJob")
    @ApiOperation("批量删除招聘职位")
    @TenantIgnore
    public CommonResult<Boolean> deleteJob(@RequestBody MemberJobidsVO memberJobidsVO) {
        jobService.deleteJob(memberJobidsVO.getIds());
        return success(true);
    }

    @PostMapping("/import-excel")
    @ApiOperation("导入招聘职位 Excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "Excel 文件", required = true, dataTypeClass = MultipartFile.class),
            @ApiImplicitParam(name = "updateSupport", value = "是否支持更新，默认为 false", example = "true", dataTypeClass = Boolean.class)
    })
    @TenantIgnore
    public CommonResult<JobImportRespVO> inputenterpriseJobExcel(@RequestParam("file") MultipartFile file,
                                                                 @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws IOException {
        // 导入 Excel
        List<EnterpriseJobImputReqVO> list=ExcelUtils.read(file,EnterpriseJobImputReqVO.class);
        log.info("[inputenterpriseJobExcel][list]:"+ JSON.toJSONString(list));
        return success(jobService.importJob(list, updateSupport));
    }



    @PutMapping("/updateRankingStatus")
    @ApiOperation("设置最新(热门)职位置顶")
    @TenantIgnore
    public CommonResult<Boolean> updateRankingStatus(@RequestBody MemberJobUpdateReqVO updateReqVO ) {
        if(null==updateReqVO.getId()||null==updateReqVO.getIsHot()||null==updateReqVO.getIsNew()){
            return error("参数错误");
        }
        jobService.updateJobNew(updateReqVO.getId(),updateReqVO.getIsNew());
        jobService.updateJobHot(updateReqVO.getId(),updateReqVO.getIsHot());
        return success(true);
    }

    @GetMapping("/getHotJobList")
    @ApiOperation("获得热门(最新)招聘职位置顶")
    @TenantIgnore
    @ApiImplicitParam(name = "type", value = "职位类型:1:热门职位,2:最新职位", required = true, dataTypeClass = Integer.class)
    public CommonResult<List<MemberJobRespVO>> getHotJobList(@RequestParam("type") Integer type ) {
        MemberJobPageReqVO pageVO=new MemberJobPageReqVO();
        if(1==type){
            pageVO.setIsHot(1);
            SortingField sortField=new SortingField();
            sortField.setField("hot_weight");
            sortField.setOrder("desc");
            pageVO.setSortField(sortField);
        }else{
            pageVO.setIsNew(1);
            SortingField sortField=new SortingField();
            sortField.setField("new_weight");
            sortField.setOrder("desc");
            pageVO.setSortField(sortField);
        }
        pageVO.setPageSize(1000);
        pageVO.setStatus("2");
        List<MemberJobDO> rankingJobList = jobService.getRankingJobList(pageVO);
        return success(MemberJobConvert.INSTANCE.convertList(rankingJobList));
    }

    @GetMapping("/updateJobNew")
    @ApiOperation("修改招聘最新职位置顶状态")
    @TenantIgnore
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "公司ID", required = true, dataTypeClass = Long.class),
            @ApiImplicitParam(name = "isNew", value = "最新职位置顶(1:是,0:否)",  dataTypeClass = Integer.class)
    })
    public CommonResult<Boolean> updateJobNew(Long id,Integer isNew) {
        jobService.updateJobNew(id,isNew);
        return success(true);
    }

    @GetMapping("/updateJobHot")
    @ApiOperation("修改招聘热门职位置顶状态")
    @TenantIgnore
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "公司ID", required = true, dataTypeClass = Long.class),
            @ApiImplicitParam(name = "isHot", value = "热门职位置顶(1:是,0:否)",  dataTypeClass = Integer.class)
    })
    public CommonResult<Boolean> updateJobHot(Long id,Integer isHot) {
        jobService.updateJobHot(id,isHot);
        return success(true);
    }

    @PutMapping("/updateRankingJobSort")
    @ApiOperation("职位置顶排序")
    @TenantIgnore
    //@PreAuthorize("@ss.hasPermission('member:news-study-info:delete')")
    public CommonResult<Boolean> updateRankingJobSort(@Valid @RequestBody RankingJobIdReqVO rankingIdReqVO ) {
        jobService.updateRankingJobSort(rankingIdReqVO);
        return success(true);
    }


}
